import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { phone, setProvince } from '../../../utils/validate'
import { useRouter } from 'vue-router'
import * as _ from 'lodash'
import {
  inboundList,
  inStoreTypePageSelect,
  deleteStore,
  disableStore,
  canNegativeStock,
} from '../../../api/store'
export default function () {
  const loading = ref(false)
  const total = ref(0)
  const tableDataList = ref(null)
  const pagination = ref()
  const ids = reactive([])
  const typeLoading = ref(false)
  const router = useRouter()
  const storeListRef = ref()
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 仓库列表搜索对象
  const storeListSearch = ref({
    dateType: 4, // 日期类型：1-时间区间，2-今天，3-本周，4-本月，5-过去三个月
    endTime: '', // 结束时间
    limit: 50,
    page: 1,
    search: '', // 关键词搜索：出库单号/收货人/手机号/制单人
    source: null, // 单据来源：1-系统单，2-工单，3-ERP单据，4-仓库移动端单据，5-第三方系统单据
    startTime: '', // 开始时间
    status: null, // 出库单状态：1-待审核，2-待出库/待发货，3-驳回，4-已完成，5-已作废/取消
    typeId: null, // 出库类型ID
  })
  // 日期类型
  const dateType = ref([
    { title: '今天', value: 2 },
    { title: '本周', value: 3 },
    { title: '本月', value: 4 },
    { title: '自定义时间', value: 1 },
  ])
  // 单据来源
  const source = ref([
    { title: '系统单', value: 1 },
    { title: '工单', value: 2 },
    { title: 'ERP单据', value: 3 },
    { title: '仓库移动端单据', value: 4 },
    { title: '第三方系统单据', value: 5 },
  ])
  // 出库单状态
  const status = ref([
    { title: '待审核', value: 1 },
    { title: '待入库', value: 2 },
    { title: '驳回', value: 3 },
    { title: '已入库', value: 4 },
    { title: '已作废', value: 5 },
  ])
  // 出库仓类型
  const storeType = ref([
    { title: '内部仓库', value: 0 },
    { title: '部门-外部仓库', value: 1 },
    { title: '工程师-外部仓库', value: 2 },
  ])
  // 收货地址类
  const receiptAddrType = ref([
    { title: '公司', value: 1 },
    { title: '部门仓库', value: 2 },
    { title: '工程师仓库', value: 3 },
  ])
  const storeForm = ref({
    address: '',
    area: '',
    canNegativeStock: false, //是否允许负库存：false-不允许，true-允许
    city: '',
    delStorePositionIds: [], //	删除的仓库仓位ID集合
    enableStorePosition: false, //是否启用仓位：false-不启用，true-启用
    id: null, //
    name: '', //仓库名称
    otherPhone: '', //其他联系方式
    outStoreExample: null, // 仓库类型：0-内部仓库，1-部门-外仓库，2-工程师-外仓库
    outStore: false, //仓库类型：false-内部仓库，true-外部仓库
    outStoreType: 1, //外部仓库类型：1-部门仓库，2-工程师仓库，当is_out_store=true时生效,示例值(1)
    province: '',
    status: false, //	仓库状态：false-启用，true-禁用
    storeNo: '', //仓库序列号，不传则系统生成
    storePositionVos: [
      //仓库仓位对象
      {
        id: null, //仓位ID，新增不必传，修改必传
        name: '', //仓位
        status: false, //仓位状态：false-启用，true-禁用
      },
    ],
    town: '',
    userName: '',
    userPhone: '',
  })
  const rulesStore = reactive({
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
    name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }], //仓库名称
    outStoreExample: [{ required: true, message: '仓库类型', trigger: ['blur', 'change'] }], //仓库类型：false-内部仓库，true-外部仓库
    userName: [{ required: true, message: '请输入仓库联系人', trigger: 'blur' }],
    userPhone: [
      { required: true, message: '请输入联系人手机号', trigger: 'blur' },
      { validator: phone(storeForm.value.userPhone), trigger: 'blur' },
    ],
    province: [
      {
        required: true,
        validator: setProvince(storeForm.value.province),
        trigger: ['blur', 'change'],
      },
    ],
  })

  // 详情页面
  const goDetailPage = (row) => {
    if (row.status == 1) {
      router.push('/storage/newin/' + row.id)
    } else {
      router.push('/storage/intb/detail/' + row.id)
    }
  }
  // 获取入库列表
  const getListOutStoreRows = (val=true) => {
    loading.value = true
    if(val&&pagination.value)pagination.value.setPage()
    storeListSearch.value.page = pagination.value ? pagination.value.current : 1 // 当面页码
    storeListSearch.value.limit = pagination.value ? pagination.value.size : 50 // 当面页码
    inboundList(storeListSearch.value).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          tableDataList.value = res.data.data.rows
          total.value = Number(res.data.data.total)
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 5000,
            plain: true,
          })
        }
      }
      loading.value = false
    })
  }
  // 获取入库下拉类型
  const outStoreType = ref([])
  const outStoreTypeValue = ref()
  const getoutStoreTypePageSelect = async (val) => {
    const data = {
      limit: 0,
      name: val,
      page: 0,
    }
    typeLoading.value = true
    await inStoreTypePageSelect(data).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          outStoreType.value = res.data.data.rows
        }
      }
    })
    typeLoading.value = false
  }
  const changeOutType = (val) => {
    outStoreTypeValue.value = val
  }
  watch(outStoreTypeValue, (n) => {
    getoutStoreTypePageSelect(n)
  })
  // 批量删除、启用、禁用
  async function changeAll(n: number, str: string) {
    if (ids.length == 0) {
      ElMessage({
        message: `请先选择要操作的选项`,
        type: 'warning',
        duration: 5000,
        showClose: true,
        plain: true,
      })
      return
    }
    ElMessageBox({
      title: '提示',
      message: `确定${str}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
      .then(async () => {
        loading.value = true
        switch (n) {
          case 1:
          case 2:
            await disableStore(ids, n == 1 ? false : true).then((res) => {
              if (res) {
                if (res.data.code == 20000) {
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: 'success',
                    plain: true,
                    duration: 5000,
                  })
                  getListOutStoreRows()
                } else {
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: 'error',
                    duration: 5000,
                    plain: true,
                  })
                }
              }
              loading.value = false
            })
            break
          case 3:
            await deleteStore(ids).then((res) => {
              if (res) {
                if (res.data.code == 20000) {
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: 'success',
                    duration: 5000,
                    plain: true,
                  })
                  getListOutStoreRows()
                } else {
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: 'error',
                    duration: 5000,
                    plain: true,
                  })
                }
              }
              loading.value = false
            })
            break
          case 4:
          case 5:
            await canNegativeStock(ids, n == 4 ? true : false).then((res) => {
              if (res) {
                if (res.data.code == 20000) {
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: 'success',
                    duration: 5000,
                    plain: true,
                  })
                  getListOutStoreRows()
                } else {
                  ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: 'error',
                    duration: 5000,
                    plain: true,
                  })
                }
              }
              loading.value = false
            })
            break
        }
      })
      .catch()
  }

  // 重置
  function clearVlaue() {
    storeListSearch.value = {
      dateType: null, //日期类型：1-时间区间，2-今天，3-本周，4-本月，5-过去在个月
      endTime: '', //	结束时间
      limit: 50,
      page: 1,
      search: '', //关键词搜索：出库单号/收货人/收货人手机号/制单人
      source: null, //单据来源：1-系统单，2-工单，3-ERP单据，4-仓库移动端单据，5-第三方系统单据
      startTime: '', //开始时间
      status: null, //出库单状态：1-待审核，2-待出库/待发货，3-驳回，4-已完成，5-已作废/取消
      typeId: null, //	出库类型ID
    }
    getListOutStoreRows()
  }

  // 时间变化时
  const dateChange = (val) => {
    if (val) {
      storeListSearch.value.startTime = val[0]
      storeListSearch.value.endTime = val[1]
    } else {
      storeListSearch.value.startTime = null
      storeListSearch.value.endTime = null
    }
    getListOutStoreRows()
  }

  return {
    dateType,
    getListOutStoreRows,
    getoutStoreTypePageSelect,
    changeOutType,
    receiptAddrType,
    goDetailPage,
    dateChange,
    source,
    status,
    outStoreType,
    typeLoading,
    storeType,
    changeAll,
    storeListRef,
    addrs,
    storeForm,
    clearVlaue,
    rulesStore,
    loading,
    total,
    pagination,
    tableDataList,
    storeListSearch,
  }
}
